<script setup lang="ts">
import { reactive, ref, unref, watch } from 'vue'
import { Form } from '@/components/Form'
import { useI18n } from '@/hooks/web/useI18n'
import { ElButton, ElLink } from 'element-plus'
import { required } from '@/utils/formRules'
import { useForm } from '@/hooks/web/useForm'
import { loginApi } from '@/api/login'
import { ucMyInfoApi, ucMyMenuAuthorityApi, ucMyAppAuthorityApi } from '@/api/my'
import { sysDictApi } from '@/api/dict'
import type { UserLoginType } from '@/api/login/types'
import { useCache } from '@/hooks/web/useCache'
import { useAppStore } from '@/store/modules/app'
import { usePermissionStore } from '@/store/modules/permission'
import { useRouter } from 'vue-router'
import type { RouteLocationNormalizedLoaded, RouteRecordRaw } from 'vue-router'
// import { ucMenuListApi } from '@/api/menu'
import { ucMenuListApi } from '@/api/uc/menu'
// import { myAuthorityApi } from '@/api/my'

const appStore = useAppStore()

const permissionStore = usePermissionStore()

const { currentRoute, addRoute, push } = useRouter()
const { wsCache } = useCache()
const { t } = useI18n()

const rules = {
  username: [required],
  password: [required]
}

const schema = reactive<FormSchema[]>([
  {
    field: 'title',
    colProps: {
      span: 24
    }
  },
  {
    field: 'username',
    label: t('login.username'),
    value: '',
    component: 'Input',
    colProps: {
      span: 24
    },
    componentProps: {
      placeholder: t('login.usernamePlaceholder')
    }
  },
  {
    field: 'password',
    label: t('密码'),
    value: '',
    component: 'InputPassword',
    colProps: {
      span: 24
    },
    componentProps: {
      style: {
        width: '100%'
      },
      placeholder: t('login.passwordPlaceholder')
    }
  },
  {
    field: 'login',
    colProps: {
      span: 24
    }
  },
  {
    field: 'tool',
    colProps: {
      span: 24
    }
  }
])

const iconSize = 30

const { register, elFormRef, methods } = useForm()

const loading = ref(false)

const iconColor = '#999'

const redirect = ref<string>('')

watch(
  () => currentRoute.value,
  (route: RouteLocationNormalizedLoaded) => {
    redirect.value = route?.query?.redirect as string
  },
  {
    immediate: true
  }
)

// 登录
const signIn = async () => {
  console.log('signIn')
  const formRef = unref(elFormRef)
  await formRef?.validate(async (isValid) => {
    if (isValid) {
      loading.value = true
      const { getFormData } = methods
      const formData = await getFormData<UserLoginType>()
      const res = await loginApi(formData)
        .catch(() => {})
        .finally(() => (loading.value = false))
      if (res) {
        // alert('登录成功，token：' + res.data.token)
        wsCache.set('token', res.data.token)
        await getMyAppAuthority() // 获取我的应用
        await getDict() // 获取字典相关数据
        await getMyInfo() // 获取当前用户信息
        await getMyMenuAuthority() //获取当前用户菜单权限
        await getMenuList() // 获取菜单的列表信息
        await getRoute() // 转化路由并跳转
      }
    }
  })
}

const getDict = async () => {
  const res = await sysDictApi({ app_id: 2 }).catch(() => {})
  if (res) {
    console.log('getDict', res)
    // 字典转化
    let newDict = grouping(res.data)
    wsCache.set('dict', newDict)
  }
}

const getMyAppAuthority = async () => {
  const res = await ucMyAppAuthorityApi({}).catch(() => {})
  if (res) {
    console.log('getMyAppAuthority', res)
  }
}

const myMenuAuthority = ref<any>({})
const getMyMenuAuthority = async () => {
  const res = await ucMyMenuAuthorityApi({ app_id: 2 })
    .catch(() => {})
    .finally(() => {})
  if (res) {
    let newMenuAuthority = change(res.data)
    console.log('getMyMenuAuthority', res, newMenuAuthority)
    myMenuAuthority.value = newMenuAuthority
    wsCache.set('myMenuAuthority', newMenuAuthority)
    // wsCache.set(appStore.getUserInfo, res.data)
  }
}

// const myAuthority = ref<any>({})
// 获取该用户权限（必须要有token后）
// const getAuthority = async () => {
//   const res = await myAuthorityApi().catch(() => {})
//   if (res) {
//     // 权限转化
//     let newAuthority = {
//       data: change(res.data.data),
//       function: change(res.data.function),
//       menu: change(res.data.menu)
//     }
//     myAuthority.value = newAuthority
//     wsCache.set('myAuthority', newAuthority)
//   }
// }

const grouping = (data: any) => {
  let map: any = {} // 处理过后的数据对象
  let temps: any = [] // 临时变量
  for (let key in data) {
    let ekey = data[key].dict_type // 根据dict_type分组
    temps = map[ekey] || [] // 如果map里面有这个key了，就取，没有就是空数组
    temps.push(data[key])
    map[ekey] = temps
  }
  return map
}

// 获取角色信息
const getMyInfo = async () => {
  const res = await ucMyInfoApi()
    .catch(() => {})
    .finally(() => (loading.value = false))
  if (res) {
    // console.log('getMyInfo', res, appStore)
    wsCache.set(appStore.getUserInfo, res.data)
  }
}

const menuData = ref<any>([])

const getMenuList = async () => {
  const res = await ucMenuListApi({ app_id: 2 })
    .catch(() => {})
    .finally(() => {})
  if (res) {
    console.log('getMenuList', res)
    menuData.value = res.data
  }
}

// 转换成直接可以查询权限的结构
const change = (data) => {
  let newData = {}
  data.forEach((item) => {
    newData[item.menu_code] = item.authority
  })
  return newData
}

const changeRoute = (data, menuAuthority) => {
  let newData: any = []
  data.forEach((item) => {
    let newItem: any = {
      path: item.path,
      component: item.component,
      name: item.menu_code,
      meta: {
        title: item.menu_name,
        hidden: item.hidden == '1' ? true : false,
        alwaysShow: item.alwaysShow == '1' ? true : false,
        noCache: item.noCache == '1' ? true : false,
        breadcrumb: item.breadcrumb == '1' ? true : false,
        affix: item.affix == '1' ? true : false,
        noTagsView: item.noTagsView == '1' ? true : false,
        canTo: item.canTo == '1' ? true : false
      }
    }
    if (item.redirect != null && item.redirect != '') {
      newItem.redirect = item.redirect
    }
    if (item.icon != null && item.icon != '') {
      newItem.meta.icon = item.icon
    }
    if (item.activeMenu != null && item.activeMenu != '') {
      newItem.meta.activeMenu = item.activeMenu
    }
    if (item.followAuth != null && item.followAuth != '') {
      newItem.meta.followAuth = item.followAuth
    }

    if (item.children != null && item.children != '') {
      newItem.children = changeRoute(item.children, menuAuthority)
      if (newItem.children.length > 0) {
        newData.push(newItem)
      }
    } else {
      if (menuAuthority[item.menu_code] == 1) {
        newData.push(newItem)
      }
    }
  })
  return newData
}

// 获取路由
const getRoute = async () => {
  const routers: any = changeRoute(menuData.value, myMenuAuthority.value) //这里转化路由的时候判断了权限
  // console.log('routers', routers)
  // console.log('99', permissionStore, addRoute, push)
  if (routers) {
    const { wsCache } = useCache()
    wsCache.set('myRouters', routers)
    await permissionStore.generateRoutes('admin', routers).catch(() => {})
    permissionStore.getAddRouters.forEach((route) => {
      addRoute(route as RouteRecordRaw) // 动态添加可访问路由表
    })
    permissionStore.setIsAddRouters(true)
    push({ path: redirect.value || permissionStore.addRouters[0].path })
  }
}

const emit = defineEmits(['setFormType'])
</script>

<template>
  <Form
    :schema="schema"
    :rules="rules"
    label-position="top"
    hide-required-asterisk
    size="large"
    class="dark:(border-1 border-[var(--el-border-color)] border-solid)"
    @register="register"
  >
    <template #title>
      <h2 class="text-2xl font-bold text-center w-[100%]">{{ t('login.login') }}</h2>
    </template>

    <template #tool>
      <div class="flex justify-end items-center w-[100%]">
        <ElLink
          type="primary"
          :underline="false"
          style="font-size: 12px"
          @click="emit('setFormType', 'register')"
          >{{ t('快速注册') }}</ElLink
        >
      </div>
    </template>

    <template #login>
      <ElButton :loading="loading" type="primary" class="w-[100%]" @click="signIn">
        {{ t('login.login') }}
      </ElButton>
    </template>

    <template #otherIcon>
      <div class="flex justify-between w-[100%]">
        <Icon
          icon="ant-design:github-filled"
          :size="iconSize"
          class="cursor-pointer anticon"
          :color="iconColor"
        />
        <Icon
          icon="ant-design:wechat-filled"
          :size="iconSize"
          class="cursor-pointer anticon"
          :color="iconColor"
        />
        <Icon
          icon="ant-design:alipay-circle-filled"
          :size="iconSize"
          :color="iconColor"
          class="cursor-pointer anticon"
        />
        <Icon
          icon="ant-design:weibo-circle-filled"
          :size="iconSize"
          :color="iconColor"
          class="cursor-pointer anticon"
        />
      </div>
    </template>
    <!-- <template #registe>
      <div class="flex justify-end w-[100%]">
        <el-button link @click="signIn"> 立即注册 </el-button>
      </div>
    </template> -->
  </Form>
</template>

<style lang="less" scoped>
:deep(.anticon) {
  &:hover {
    color: var(--el-color-primary) !important;
  }
}
</style>
